package ihm.actions.itemTree;

import java.util.List;

import ihm.views.main.ItemsTree;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import systems.languages.MultiLanguages;
import systems.rpgBuilder.Item;

/**
 * This class contains the behavior of the program when the user select an item
 * in the Item Tree.
 * @author Baptiste Legrand & Benjamin Orman
 * @version 1.0
 */
public class SelectedItemAction implements TreeSelectionListener {
  //Local copy of the itemsTree attached to this Action
  private ItemsTree itemTree;
  //The item selected in the tree
  private Item itemSelected = null;
  
  /**
   * Constructor of the action to execute when the user select an item in the
   * item tree.
   * @param itemsTree - The ItemsTree linked to this action.
   */
  public SelectedItemAction(ItemsTree itemsTree)
  {
    this.itemTree = itemsTree;
  }

  @Override
  public void valueChanged(TreeSelectionEvent e) {    
    //Returns the last path element of the selection.
    //This method is useful only when the selection model allows a single selection.
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.itemTree.getTree().getLastSelectedPathComponent();

    //If the selected node is null ...
    if (node == null)
      //... then we do nothing
      return;
    //... else ...
    Object nodeInfo = node.getUserObject();
    // Get the name of the item
    String itemName = (String)nodeInfo;
    //System.out.println("Item selected : "+itemName); //LOG
    findItem(itemName);
    //TODO : Treat the case where this.itemSelected is 'null'
    //Notify that the item selected changed.
    this.itemTree.getController().notifyItemTypeChanged(this.itemSelected);
  }

  /**
   * This function try to find an item on an the item list according to its 
   * name.
   * If this function does not find the item called <i>itemName</i> then the
   * itemSelected is set to null, else it will contains the Item.
   * @param itemName - The name of the Item to find.
   */
  private void findItem(String itemName)
  {
    this.itemSelected = null;
    findRecursiveItem(this.itemTree.getItemList(), itemName);
  }

  /**
   * This function is the second part of the findItem method. This one works
   * recursivly on each item of the item list given in parameter.
   * @param list - The List of Item where the Item named <i>itemName</i> could be.
   * @param itemName - The name of the item the program are looking for.
   */
  private void findRecursiveItem(List<Item> list, String itemName)
  {
    for (Item item : list)
    {
      if(MultiLanguages.getProperties(item.getMultiLangueName()).equalsIgnoreCase(itemName))
      {
        this.itemSelected = item;
        return;
      }else{
        findRecursiveItem(item.getSubItemsList(), itemName);
      }
    }
  }
}
